import 'dart:math';

import 'package:flutter/material.dart';

import '../../widgets/list_state_page.dart';
import '../../models/article_model.dart';
import '../../models/category_model.dart';
import '../../widgets/article_widget.dart';
import '../../application.dart';

class ListPage extends StatefulWidget {
  final String? channel;
  final int? cateId;

  ListPage({Key? key, required Map<String, dynamic> arguments})
      : channel = arguments['channel'],
        cateId = arguments['cate'],
        super(key: key);

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
  late CategoryModel channel;
  late List<CategoryModel> categories;
  bool initialized = false;

  int cateId = 0;

  @override
  void initState() {
    super.initState();
    if (widget.cateId != null) {
      cateId = widget.cateId!;
    }
    initialize();
  }

  @override
  Widget build(BuildContext context) {
    if (!initialized) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    if (categories.isEmpty) {
      return _ListWidget(cateId: cateId);
    }
    return DefaultTabController(
      initialIndex:
          max(categories.indexWhere((element) => element.id == cateId), 0),
      length: categories.length,
      child: Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          title: TabBar(
            isScrollable: true,
            tabs: categories
                .map<Widget>((cate) => Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      child: Text(
                        cate.title,
                        softWrap: false,
                      ),
                    ))
                .toList(),
          ),
        ),
        body: SafeArea(
          child: TabBarView(
            children: categories
                .map<Widget>(
                  (cate) => _ListWidget(cateId: cate.id),
                )
                .toList(),
          ),
        ),
      ),
    );
  }

  Future<void> initialize() async {
    final cates = await app.getCategories();
    if (cates[0] != null) {
      channel = cates[0]!.firstWhere(
          (element) => element.name == widget.channel,
          orElse: () => CategoryModel());
      categories = cates[channel.id]!;
      initialized = true;
      if (mounted) {
        setState(() {});
      }
    }
  }
}

class _ListWidget extends StatefulWidget {
  final int cateId;
  const _ListWidget({Key? key, required this.cateId}) : super(key: key);

  @override
  _ListWidgetState createState() => _ListWidgetState();
}

class _ListWidgetState extends ListStatePage<_ListWidget, ArticleModel> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return buildListView();
  }

  @override
  String get apiUrl => 'article/get_list';

  @override
  @override
  Widget buildItem(ArticleModel item) {
    return ArticleWidget(item);
  }

  @override
  Map<String, dynamic> get requestArgs => {'cate': widget.cateId};

  @override
  ArticleModel transItem(item) {
    return ArticleModel.fromJson(item as Map?);
  }
}
